package com.tang.lts.core.store;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author Tang
 * @classname TxConnectionFactory
 * @description [  ]
 * @date 2022/5/6 15:03
 */
public class TxConnectionFactory {

    private static final ThreadLocal<Connection> TRANSACT_CONN = new ThreadLocal<>();

    static Connection getCurrentCon() {
        return TRANSACT_CONN.get();
    }

    static Connection getTxConnection(DataSource dataSource) {
        Connection con = TRANSACT_CONN.get();
        if (con != null) {

        }
        try {
            con = dataSource.getConnection();
            con.setAutoCommit(false);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        TRANSACT_CONN.set(con);
        return con;
    }

    static void closeTx(Connection conn) {
        try {
            if (conn != null) {
                if (conn.isReadOnly()) {
                    conn.setReadOnly(false);
                }
                conn.close();
            }
        } catch (SQLException e) {
           e.printStackTrace();
        } finally {
            TRANSACT_CONN.set(null);
        }
    }
}